from os import path, system, getcwd, listdir,remove,scandir
import math
import json
import json
import json as js
import sys
import time
import re
import logging
import streamlit.components.v1 as components
import time
import matplotlib.pyplot as plt
#import blacstab2
import demjson
import os
import socket
import yaml
import pandas as pd
from collections import OrderedDict
import streamlit as st
import pyvista as pv
from stpyvista import stpyvista
#import hiplot as hip
import numpy as np
import requests
import random
from dotenv import load_dotenv
import plotly.graph_objects as go
from utils import Cursor
import mpld3
import streamlit.components.v1 as components
from mpld3 import plugins
from streamlit_navigation_bar import st_navbar
from dotenv import load_dotenv
#from BeaverFramework.beavertools import json2yaml, yaml2json
import plotly.express as px
from ruamel.yaml import YAML

#This Application codes from Michael Zhang
load_dotenv()
user_name = os.getenv("USER_NAME")
data_base = os.getenv("BBS_BASE")
run_base = os.getenv("RUN_BASE")
user_log = os.getenv("SYS_LOG")
st.set_page_config(layout="wide")

m = st.markdown("""
<style>
div.stButton > button:first-child {
    background-color: #0099ff;
    color:#ffffff;
}
div.stButton > button:hover {
    background-color: #00ff00;
    color:#ff0000;
    }
</style>""", unsafe_allow_html=True)
# basic dir in .env

new_chords = {}
sections = {}
each_sec = {}
cmp_base = {}
display = True
hostnm=socket.gethostname()
log_path = path.join(getcwd(),'bbs.log')
logger = logging.getLogger("BBS")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(log_path)  # file to adding log info
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
#def edit_cell(row, column,df, options):
#    selected_value = st.selectbox('', options, index=options.index(df.at[row, column]))
#    df.at[row, column] = selected_value
def download_file(file_path, file_name):
    with open(file_path, 'rb') as file:
        file_bytes = file.read()
    st.download_button(
        label="下载模版文件",
        data=file_bytes,
        file_name=file_name,
        mime="application/text-plain"
    )

def main():
    if hostnm == "mich":
        dir_path_sys=path.join('/home/luban/NAS', user_name, 'RunData/sys')
        dir_path_shape=path.join('/home/luban/NAS', user_name, 'RunData/aero_shape')
        dir_path_struct=path.join('/home/luban/NAS', user_name, 'RunData/Struct')
        dir_path_stab2=path.join('/home/luban/NAS', user_name, 'RunData/stab2')
        dir_path_fast=path.join('/home/luban/NAS', user_name, 'RunData/fast')
    else:
        dir_path_sys=path.join('/home/luban/NAS', user_name, 'RunData/sys')
        dir_path_shape=path.join('/home/luban/NAS', user_name, 'RunData/aero_shape')
        dir_path_struct=path.join('/home/luban/NAS', user_name, 'RunData/Struct')
        dir_path_stab2=path.join('/home/luban/NAS', user_name, 'RunData/stab2')
        dir_path_fast=path.join('/home/luban/NAS', user_name, 'RunData/fast')
    index_file = []
    #page = st_navbar( ['File', 'Airfoils', 'interMethod', 'MakeGeo', 'Lamplan', 'Material', 'BuildBlade','meshBlade','Stiffness','AEP','Stability'])
    page = st_navbar(["SysIters","Shapes", "Airfoils","MakeGeo",\
        "Lamplan","Material","Stiffness","Stability","StrainStress"])
    col1, col2, col3= st.columns(3)
    if page == "SysIters":
        with col3:
            file_path = os.path.join(dir_path_shape,"templates/download/menu_file_system.yml")
            file_name = "menu_file_system.yml"
            st.write("查看系统变量文件")
            download_file(file_path, file_name)
        yamlfile = os.path.join(dir_path_sys,"system.yml")
        config = yaml.load(open(yamlfile, "r"), Loader=yaml.CLoader)
        objectives = config["objectives"]
        #AEP [GWh]
        min_aep_hours = objectives["min_aep_hours"]
        st.divider()
        sl1,sl2,sl3,sl4 = st.columns(4)
        with sl1:
            Turbine_power_rated = st.text_input("min_aep_hour",value=min_aep_hours)
            #Aero CPmax [-] e.g. >0.47
            cp_max = st.text_input("cp_max",value=objectives["cp_max"])
            #Blade mass [ton] e.g. 50
            blade_mass_total = st.text_input("blade_mass_total",value=objectives["blade_mass_total"])
            #Blade cost [RMB] e.g. 8 mil for 3 blades
            #blade_cost: 8
            #Blade load [MNm] e.g. 90
            #max_loads : 
            #Blade thrust [MN] e.g. xx
            max_tip_speed = st.text_input("max_tip_speed",value=objectives["max_tip_speed"])
            #load envelope max , unit
            #load_evlop: [('xxx_Mxy',1500),(xxxx_Mxy",130)]
            environment = config["environment"]
            #Average wind speed at hub height for Design [m/s] e.g. 10
            wind_speed_avg = st.text_input("wind_speed_avg",value=environment["wind_speed_avg"])
            #Weibull shape facor, k [-] e.g. 2.3
            A_value = st.text_input("A value",value=environment["a_value"])
            K_value = st.text_input("K value",value=environment["k_value"])
            #Vref [m/s] e.g. 57
            Vref = st.text_input("Vref",value=environment["Vref"])
            #Reference TI [%] e.g. 10
            TI = st.text_input("Turblence ",value=environment["TI"])
        with sl2:
            turbine = config["turbine"]
            #Rated power, P [MW] e.g. 16
            Turbine_power_rated = st.text_input("Turbine_power_rated",value=turbine["Turbine_power_rated"])
            #Rotor diameter range, RD [m] e.g. 250-253
            rotor_diameter = st.text_input("root_diameter",value=turbine["rotor_diameter"])
            hub_diameter = st.text_input("hub_diameter",value=turbine["hub_diameter"])
            #Hub height, HH [m] e.g. 150
            hub_height = st.text_input("hub_height",value=turbine["hub_height"])
            #Cut-in wind speed [m/s] e.g. 4
            start_speed = st.text_input("start_speed",value=turbine["start_speed"])
            last_speed = st.text_input("last_speed",value=turbine["last_speed"])
            rated_wind_speed = st.text_input("rated_wind_speed",value=turbine["rated_wind_speed"])
            #Loss model [%] e.g. 10% or loss model in hawc2/bladed format
            #Average air density [kg/m3] e.g. 1.2
            air_density = st.text_input("air_density",value=environment["air_density"])
            #Minimum air density [kg/m3] e.g. 0.9
            air_density_min = st.text_input("air_density_min", value=environment["air_density_min"])

            
    if page == "Shapes":
        #Shape_Existing, Shape_upload_JSON, Shape_upload_YAML, save_all, logOFF = st.tabs(["Shape_Existing","Shape_upload_JSON" ,"Shape_upload_YAML","save_all","logOFF"]) 
        with col1:
            option = st.selectbox("系统选择",("Shape_Existing","Shape_upload_JSON" ,"Shape_upload_YAML","save_all","logOFF"))
        if option == "Shape_upload_JSON":
            data_json = {}                 
            with col3:
                file_path = os.path.join(dir_path_shape,"templates/download/menu_file_json_shape.json")
                file_name = "menu_file_json_shape.json"
                download_file(file_path, file_name)
            with col2:
                uploaded_file = st.file_uploader("上传JSON格式文件，模版可下载",type=["json"],help="shape file has diameter,chord,thichness,Twist") 
            if uploaded_file is not None: 
                data_json= pd.read_json(uploaded_file)
                sections = data_json['Blade']['Sections']
                my_output_dir = os.path.join("/home/mich/NAS", user_name,"RunData/aero_shape/inputs/blade_shape")
                my_file =  os.path.join(my_output_dir,uploaded_file.name)
                #save to inputs
                with open(my_file, 'w', encoding=u'utf-8', errors='ignore') as fp:
                    my_dict = data_json.to_dict()
                    #st.write(my_dict)
                    data_json = my_dict
                    json.dump(my_dict, fp, indent=4)
                    fp.close()
                    #st.write("write success path!",my_file)
            else:   
                yamlfile = os.path.join(run_base, "Struct","s123_lam.yml")
                config = yaml.load(open(yamlfile, "r"), Loader=yaml.CLoader)
                shape_base = config["planform"]
                Chord_base = shape_base["chord"]
                Thick_base = shape_base["thickness"] 
                Twist_base = shape_base["twist"]  
                list_Chord = []
                list_Thick_abs = []
                list_Twist = []
                list_Thickness = []
                radius = []
                all_list = []
                for (chord, thick, twist) in zip(Chord_base, Thick_base, Twist_base):
                    radius.append(chord[0])
                    list_Chord.append(chord[1])
                    list_Thickness.append(thick[1])
                    list_Twist.append(twist[1])
                    list_Thick_abs.append((thick[1])*float(chord[1]))
                data_json= pd.read_json(os.path.join(data_base,"aero_shape/inputs/blade_shape/tsrv6_2023.json"))
                sections = data_json['Blade']['Sections']
                #st.write(list_Thick_abs)
                shows = True
        elif option == "Shape_upload_YAML":
            data_json = {}           
            with col3:
                file_path = os.path.join(dir_path_shape,"templates/download/menu_file_yaml_shape.yml")
                file_name = "menu_file_yaml_shape.yml"
                download_file(file_path, file_name)
            with col2:
                uploaded_file = st.file_uploader(" 上传yaml文件",type=["yml"]) 
            if uploaded_file is not None: 
                yml_read = uploaded_file.read().decode( "utf-8")
                #st.write(type(yml_read))
                my_output_dir = os.path.join("/home/mich/NAS", user_name,"RunData/aero_shape/inputs/blade_shape")
                name_only = os.path.splitext(uploaded_file.name)[0]
                #full_name =name_only + ".json"
                my_file = os.path.join(my_output_dir,name_only)
                data_json = {}
                #st.write(data_json)
            else:
                yamlfile = os.path.join(run_base, "Struct","s123_lam.yml")
                config = yaml.load(open(yamlfile, "r"), Loader=yaml.CLoader)
                shape_base = config["planform"]
                Chord_base = shape_base["chord"]
                Thick_base = shape_base["thickness"] 
                Twist_base = shape_base["twist"]  
                #st.write(Thick_base)
                list_Chord = []
                list_Thick_abs = []
                list_Twist = [] 
                list_Thickness = []
                radius = []
                all_list = []
                mylist=[]
                blade_lgn = 120.0
                for (chord, thick, twist) in zip(Chord_base, Thick_base, Twist_base):
                    radius.append(int(chord[0]*blade_lgn))
                    #list_Chord.append(chord[1])
                    #list_Thickness.append(thick[1])
                    #list_Twist.append(twist[1])
                    #list_Thick_abs.append(int(thick[1])*int(chord[1]))
                    #make a dict and assign to list
                    new_json = {}
                    new_json["Dist_from_root"] = chord[0]*blade_lgn
                    new_json["ab_Chord"] = chord[1]
                    new_json["Twist"] = twist[1]
                    new_json["rel_Thickness"] = thick[1]
                    new_json["ab_Thickness"] = thick[1]*chord[1]
                    mylist.append(new_json)
                    #st.write(new_json)
                    #n_sections = st.number_input("sections of blade",value=len(radius),help="how many divided in blade length, eg:80")
                    #radii = st.text_input("change  from start,stop,sections along blade radical","np.linspace(0,7,20).tolist() + np.linspace(7.4,121, 120).tolist()")
                #assing to blade
                #st.write(mylist)
                sections = mylist
        
        elif option == "Shape_Existing": 
            with col2:
                #st.write("选择一个初始形状叶片")
                data_json = {}
                list_inputs_dir = os.path.join(data_base,"aero_shape/inputs/blade_shape")
                list_files = os.listdir(list_inputs_dir)
                file_ch = st.selectbox("选择一个叶片形状", (list_files))
                ext_file = os.path.join(list_inputs_dir,file_ch)
                data_json= pd.read_json(ext_file) 
                
                sections = data_json['Blade']['Sections'] 
                #st.write(sections)           
                shows = True         
                #st.write("show_xx ",show_secs,show_rel_Thick,show_twist)
        elif option == "save_all":
            my_export_name = st.text_input("input a zip file name eg. my_zip")
            #os.system("./run_zip_save_project.sh %s %s" % (user_name, my_export_name))
            shows = False
        elif option == "logOFF":
            quit()
        if (option == "Shape_upload_JSON" or option =="Shape_Existing" or option =="Shape_upload_YAML"):
            #sections = data_json['Blade']['Sections']
            #st.write(sections)
            ChordThick,abs_Chord,abs_Thick,Twist,rel_Thick = st.tabs(["ChordThick","abs_Chord","abs_Thick","Twist","rel_Thick"])
            list_Chord = []
            list_Thick_abs = []
            list_Twist = []
            list_Thickness = []
            radius = []
            all_list = []
            #st.write(sections)
            for section in sections:
                list_Chord.append(section["ab_Chord"])
                list_Thick_abs.append(section["ab_Thickness"])
                list_Twist.append(section["Twist"])
                list_Thickness.append(section["rel_Thickness"]) 
                #st.write(section["rel_Thickness"])
                radius.append(section["Dist_from_root"])
            #st.write(list_Thickness)
            all_list.append(list_Chord)
            all_list.append(list_Thick_abs)     
            df = pd.DataFrame(all_list,dtype=float,columns=radius)
            df.index= ["Chord","Thick_abs"]  
            sect_save = True
            if sect_save:
                    all_list.append(list_Twist)
                    all_list.append(list_Thick_abs)
                    all_list.append(list_Thickness)
                    df.index= ["Chord","Thick_abs"]  
                    df.to_csv("./read_json_df.csv")
            #st.write('Aeroshape Regarding , shape analysis ',df.T)
            x_size = int(np.max(np.array(radius))) + 5 
            y_size = int(np.max(np.array(list_Chord))) + 1
            show_top = True
            x = np.array(radius)
            y = np.array(df.T)
            my_labels = ["Chord","abs_thickness"]
            with ChordThick:
                fig1 = plt.figure(figsize=(15,5))
                #plt.subplot(411)
                plt.plot(x,y, color='tab:blue',marker='.')
                plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.grid(True,axis='y',which='both',linestyle='--',color='lightblue',alpha=0.5)
                plt.xticks(np.arange(0,x_size,5))
                plt.yticks(np.arange(0,y_size,0.5))
                plt.xlabel("blade raduis m")
                plt.ylabel("absolute Chord ")
                plt.legend(loc="best", labels=my_labels)
                plt.tight_layout()
                for axes in fig1.axes:
                    for line in axes.get_lines():
                        # get the x and y coords
                        xy_data = line.get_xydata()
                        labels = []
                        for x, y in xy_data:
                            # Create a label for each point with the x and y coords
                            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
                            labels.append(html_label)
                        # Create the tooltip with the labels (x and y coords) and attach it to each line with the css specified
                        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
                        # Since this is a separate plugin, you have to connect it
                        plugins.connect(fig1, tooltip)
                fig_html = mpld3.fig_to_html(fig1)
                components.html(fig_html,width=2600, height=490)                   
            with Twist:
                y2 = np.array(list_Twist)
                x =  np.array(radius)
                y_size = int(np.max(np.array(list_Twist))) + 1
                x_size = int(np.max(np.array(radius)))+5
                fig2 = plt.figure(figsize=(15,5))
                plt.plot(x,y2, color='tab:blue',marker='.')
                plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.grid(True,axis='y',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.xticks(np.arange(0,x_size,5))
                plt.yticks(np.arange(0,y_size,1))
                plt.xlabel("blade raduis m")
                plt.ylabel("Relative Thickness % ")
                plt.legend(loc="best", labels="Twist Angle")
                plt.tight_layout()
                for axes in fig2.axes:
                    for line in axes.get_lines():
                        # get the x and y coords
                        xy_data = line.get_xydata()
                        labels = []
                        for x, y in xy_data:
                            # Create a label for each point with the x and y coords
                            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
                            labels.append(html_label)
                        # Create the tooltip with the labels (x and y coords) and attach it to each line with the css specified
                        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
                        # Since this is a separate plugin, you have to connect it
                        plugins.connect(fig2, tooltip)
                fig_html = mpld3.fig_to_html(fig2)
                components.html(fig_html,width=2600, height=499)
            with abs_Thick:          
                y_size = int(np.max(np.array(list_Thick_abs)))
                #st.write(y_size)
                fig3 = plt.figure(figsize=(15,5))
                x = np.array(radius)
                y1 = np.array(list_Thick_abs)
                plt.plot(x,y1, color='tab:blue',marker='.')
                plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.grid(True,axis='y',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.xticks(np.arange(0,x_size,5))
                plt.yticks(np.arange(0,y_size,0.5))
                plt.xlabel("blade raduis m")
                plt.ylabel("absolute Thickness % ")
                plt.legend(loc="best", labels="absolute Thickness")
                plt.tight_layout()
                for axes in fig3.axes:
                    for line in axes.get_lines():
                        # get the x and y coords
                        xy_data = line.get_xydata()
                        labels = []
                        for x, y in xy_data:
                            # Create a label for each point with the x and y coords
                            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
                            labels.append(html_label)
                        # Create the tooltip with the labels (x and y coords) and attach it to each line with the css specified
                        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
                        # Since this is a separate plugin, you have to connect it
                        plugins.connect(fig3, tooltip)
                fig_html = mpld3.fig_to_html(fig3)
                components.html(fig_html,width=2600, height=499)
            
            with rel_Thick: 
                #st.write(list_Thickness)         
                y_size = int(100*np.max(np.array(list_Thickness)))
                fig4 = plt.figure(figsize=(15,5))
                x = np.array(radius)
                y1 = np.array(list_Thickness)*100
                plt.plot(x,y1, color='tab:blue',marker='.')
                plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.grid(True,axis='y',which='both',linestyle='--',color='gray',alpha=0.5)
                y_size = 100
                plt.xticks(np.arange(0,x_size,5))
                plt.yticks(np.arange(0,y_size,5))
                plt.xlabel("blade raduis m")
                plt.ylabel("Relative Thickness % ")
                plt.legend(loc="best", labels="Reletive Thickness")
                plt.tight_layout()
                for axes in fig4.axes:
                    for line in axes.get_lines():
                        # get the x and y coords
                        xy_data = line.get_xydata()
                        labels = []
                        for x, y in xy_data:
                            # Create a label for each point with the x and y coords
                            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
                            labels.append(html_label)
                        # Create the tooltip with the labels (x and y coords) and attach it to each line with the css specified
                        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
                        plugins.connect(fig4, tooltip)
                fig_html = mpld3.fig_to_html(fig4)
                components.html(fig_html,width=2600, height=499)
                        # Since this is a separate plugin, you have to connect it
            with abs_Chord:
                y2 = np.array(list_Chord)
                x =  np.array(radius)
                y_size = int(np.max(np.array(list_Chord))) + 1
                x_size = int(np.max(np.array(radius)))+5
                fig5 = plt.figure(figsize=(15,5))
                plt.plot(x,y2, color='tab:blue',marker='.')
                plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.grid(True,axis='y',which='both',linestyle='--',color='gray',alpha=0.5)
                plt.xticks(np.arange(0,x_size,5))
                plt.yticks(np.arange(0,y_size,0.5))
                plt.xlabel("blade raduis m")
                plt.ylabel("absolute Thickness % ")
                plt.legend(loc="best", labels="absolute Thickness")
                plt.tight_layout()
                for axes in fig5.axes:
                    for line in axes.get_lines():
                        # get the x and y coords
                        xy_data = line.get_xydata()
                        labels = []
                        for x, y in xy_data:
                            # Create a label for each point with the x and y coords
                            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
                            labels.append(html_label)
                        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
                        plugins.connect(fig5, tooltip)
                fig_html = mpld3.fig_to_html(fig5)
                components.html(fig_html,width=2600, height=499)
    elif page == "Airfoils":
        #assign to thickness on  screen 
        foils_dir = os.path.join(data_base, "airfoils/foils")
        #read foil files
        #upload_foil,foil_analysis,foil_assign = st.tabs(['upload_foil','foil_analysis','foil_assign'])
        foil_analysis, foil_assign, upload_foil = st.columns(3)
        with upload_foil:  
            uploaded_file = st.file_uploader("上传翼型文件.dat",type=["dat"]) 
            if uploaded_file is not None: 
                #f1 = open(uploaded_file,'r')
                datain = pd.read_csv(uploaded_file)
                st.write(datain)
                time.sleep(90)
                my_output_dir = os.path.join(data_base, "airfoils/foils")
                my_file =  os.path.join(my_output_dir,uploaded_file.name)
                #plot the profile
                df = pd.read_csv(my_file, sep='\s+', skiprows=1, names=['x','y'])
                #st.write(df['x'])
                x = pd.array(df['x'])
                y = pd.array(df['y'])
                myfig = uploaded_file.name
                plt.clf()
                fig  = plt.figure(1,figsize=(6,2),dpi=20)
                plt.plot(x,y)
                plt.legend(loc="best",labels=['x','y'])
                plt.tight_layout()
                st.pyplot(fig)
                datain.to_csv(my_file, index=False)
                #st.write("file uploaded")
            else:
                #show a profile 
                my_output_dir = os.path.join(data_base, "airfoils/foils")
                #filename="NACA_0012_180.dat"
                filename = "NACA_0012_180.dat"
                df = pd.read_csv(os.path.join(my_output_dir,filename),sep='\s+', skiprows=1, names=['x','y'])
                #st.write(df['x'])
                x = pd.array(df['x'])
                y = pd.array(df['y'])
                fig = plt.figure(1,figsize=(6,2),dpi=20)
                plt.plot(x,y)
                plt.legend(loc="best",labels=['x','y'])
                plt.tight_layout()
                st.pyplot(fig)
        with foil_analysis:
            air_file_list = []
            for file in os.listdir(foils_dir):
                air_file_list.append(file)
            air_select = st.selectbox("选择一个翼型分析",(air_file_list))
            my_output_dir = os.path.join(data_base, "airfoils/foils")
            if air_select is not None:
                this_dat = os.path.join('./airfoils',air_select)
                this_Re = st.number_input("Re",value=1e6,help="Re input, eg. 1e6")
                this_polar = air_select
                this_aoa = st.number_input("AOA",value=0,help=" angle of attack, eg: 0 or 1 or 0 2 4 6 ")        
                #os.system("./xfoil_shell.sh %s %s %s %s" % (this_dat, this_Re, this_polar, this_aoa))
                #time.sleep(2)
                #plot here
                #st.image("1.png")
                #df1 = pd.read_csv(os.path.join("outputs/this_polar", this_polar), skiprows=6)
                #st.write(df1)
            else:
                this_dat =  "./airfoils/naca0017.dat"
                this_Re = 1e6
                this_polar = os.path.basename(this_dat).split('.')[0] + ".txt" 
                this_aoa = 2
            if st.button("分析"):
                os.system("./xfoil_shell.sh %s %s %s %s" % (this_dat, this_Re, this_polar, this_aoa))
                time.sleep(2)
                st.image("1.png")
        with foil_assign:
            st.write("编辑一组翼型去使用")     
            csv_template = os.path.join(dir_path_shape,"templates/menu_airfoil_assign.csv")
            #upload a csv which has a foils list 
            #up_csv_file = st.file_uploader("上传一个csv文件，有翼型组 ",type=["csv"],help="customer foils list same with here") 
            test = True
            if test: 
                thick_name = [] 
                foil_name = []  
                while True:
                    th_ch = st.text_input("relative_thickness_input",value=0.21)
                    foil_ch = st.selectbox("根据以上厚度选择翼型", (air_file_list))
                    thick_name.append(th_ch)
                    foil_name.append(foil_ch)
                    if st.button("选择完成"):
                        #write to .yaml file of 
                        for t_name,f_name in thick_name,foil_name:
                            st.write(t_name,f_name)
                    #df = pd.read_csv(csv_template)
                    #st.data_editor(df)
            else:                    
                yamlfile = os.path.join(dir_path_struct,"inputs/s123_lam.yml")
                config = yaml.load(open(yamlfile, "r"), Loader=yaml.CLoader)
                foil_files_list = config["aero"]["airfoils"]
                new_df = (pd.DataFrame(foil_files_list,index=["airfoil-name"])).T
                def edit_cell(row, column,df, options):
                    selected_value = st.selectbox('', options, index=options.index(df.at[row, column]))
                    df.at[row, column] = selected_value
                st.write("please click upper top to download when you are edit this table",new_df)                
    elif page == "MakeGeo":
        #paravewweb to show .vtk file
        col1, col2,col3,col4, col5, col6 = st.columns(6)
        
        yamlfile = os.path.join(run_base, "Struct","s123_lam.yml")
        config = yaml.load(open(yamlfile, "r"), Loader=yaml.CLoader)
        shape_base = config["planform"]
        Chord_base = shape_base["chord"]
        Thick_base = shape_base["thickness"] 
        Twist_base = shape_base["twist"]  
        list_Chord = []
        list_Thick_abs = []
        list_Twist = [] 
        list_Thickness = []
        radius = []
        all_list = []
        for (chord, thick, twist) in zip(Chord_base, Thick_base, Twist_base):
            radius.append(chord[0])
            list_Chord.append(chord[1])
            list_Thickness.append(thick[1])
            list_Twist.append(twist[1])
            list_Thick_abs.append((thick[1])*float(chord[1]))
        #with col1:
        radii = st.text_input("change  from start,stop,sections along blade radical","np.linspace(0,7,20).tolist() + np.linspace(7.4,121, 120).tolist()")
            #n_sections = st.number_input("sections of blade",value=len(radius),help="how many divided in blade length, eg:80")
        with col2:    
            polate_method = st.selectbox("select spline method",("Linear", "Kochanek", "Cardina" , "SmoothCurve"))
        with col3:
            spspan = st.number_input("input spspan number",value=config["planform"]["npspan"],help="span wise mesh number of sections")
        with col4:
            spchord = st.number_input("input spcord number",value=config["planform"]["npchord"],help="chord wise mesh number of sections")
        #pl1,pl2 = st.columns(2)
        #config["planform"]["n_sections"] = n_sections
        config["mesh"]["radii"] = radii
        config["planform"]["npspan"] = spspan
        config["planform"]["npchord"] = spchord 
        #st.write(config)
        #time.sleep(30)
        configfile = os.path.join(run_base, "Struct", "s123_lam.yml")
        #    dumpfile.write(yaml.dump(config))     
        y = YAML()
        y.dump(config,open(configfile, "w"))

        with col1:
            if st.button("create 3D mesh shell"):
                    this_cmd = "geom"
                    os.system("./run_all.sh %s" % (this_cmd))
                    this_cmd ="mesh"
                    os.system("./run_all.sh %s" % (this_cmd))   
                    time.sleep(5)
        #3D with stpyvista
        # Load your .vtk file
        mesh = pv.read(os.path.join(run_base, "Struct","temp_b3ps_portable/test_blade_shell.vtp"))
        ## Initialize a plotter object
        plotter = pv.Plotter(window_size=[1500,1000])
        x, y, z = mesh.cell_centers().points.T
        #x,y,z = mesh.cell_left().points.T
        mesh["My scalar"] = z
        ## Add mesh to the plotter
        plotter.add_mesh(
            mesh,
            scalars="My scalar",
            cmap="prism",
            show_edges=True,
            edge_color="#001100",
            ambient=0.01,)
        ## Final touches
        plotter.view_isometric()
        plotter.background_color = 'white'
        ## Send to streamlit
        stpyvista(plotter)
        st.image(os.path.join(run_base, "Struct","temp_b3ps_portable/test_blade.png"))
        
        #with pl2:


    elif page == "Lamplan":
        st.markdown(""":blue[可以上传你的铺层文件和实时修改，修改后点击右上角下载]""")
        cl1,cl2,cl3 = st.columns(3)
        with cl1:
            up_csv_file = st.file_uploader("upload a laminate plan .csv file ",type=["csv"],help="customer .csv file to upoload here") 
        
        if up_csv_file is None:
            df = pd.read_csv(os.path.join(run_base, "Struct","lamplan_S123_600_2.csv"))
            st.data_editor(df)
        if up_csv_file is not None:
            df = pd.read_csv(up_csv_file)
            st.data_editor(df)
        st.write("please click upper top to download when you are edit this table")  
        pass
    elif page == "Material":
        st.markdown(''':blue[---材料特性一般很少变化，这里可以修改后] ''')
        with open(os.path.join(run_base, "Struct", "materials_v9.yml"), 'r') as file:
            data = yaml.safe_load(file)
            st.write(data)
    elif page == "StrainStress":
        #readn yaml file and shows the deformation of a blade        
        st.markdown(''':blue[---确定前面的菜单都有选择，然后点击蓝色按钮] ''')
        if  st.button("make Strain"):
            this_cmd = "build"
            os.system("./run_all.sh  %s" % (this_cmd))
            st.write("blade will be done at soon, left navigator menu could do 3D detail view")
        #load dx,dy from .yml file
        with open(os.path.join(run_base,"Struct","s123_lam.yml"), 'r') as file:
            data = yaml.safe_load(file)
        dx = data["planform"]["dx"]
        dy = data["planform"]["dy"]
        blade_lgn = data["planform"]["blade_lgn"]
        
        #get dx dy list
        list_dy = []
        list_dx = []
        radius = []
        for (ddx, ddy) in zip(dx, dy):
            radius.append(ddx[0]*blade_lgn)
            list_dx.append(ddx[1])
            list_dy.append(ddy[1])
        
        #show 
        #y2 = np.array(list_Chord)
        #x =  np.array(radius)
        #y_size = int(np.max(np.array(list_Chord))) + 1
        #x_size = int(np.max(np.array(radius)))+5
        #fig5 = plt.figure(figsize=(15,5))
        #plt.plot(x,y2, color='tab:blue',marker='.')
        #plt.grid(True,axis='x',which='both',linestyle='--',color='gray',alpha=0.5)
        #plt.grid(True,axis='y',which='both',linestyle='--',color='gray',alpha=0.5)
        #plt.xticks(np.arange(0,x_size,5))
        #plt.yticks(np.arange(0,y_size,0.5))
        #plt.xlabel("blade raduis m")
        #plt.ylabel("absolute Thickness % ")
        #plt.legend(loc="best", labels="absolute Thickness")
        #plt.tight_layout()
        #for axes in fig5.axes:
        #    for line in axes.get_lines():
        #        # get the x and y coords
        #        xy_data = line.get_xydata()
        #        labels = []
        #        for x, y in xy_data:
        #            # Create a label for each point with the x and y coords
        #            html_label = f'<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> </thead> <tbody> <tr> <th>x</th> <td>{x}</td> </tr> <tr> <th>y</th> <td>{y}</td> </tr> </tbody> </table>'
        #            labels.append(html_label)
        #        tooltip = plugins.PointHTMLTooltip(line, labels, css=css)
        #        plugins.connect(fig5, tooltip)
        #fig_html = mpld3.fig_to_html(fig5)
        #components.html(fig_html,width=2600, height=499)
        m1,m2,m3 = st.columns(3)
        with m2:
            st.write(data["planform"])
        with m1:
            st.write(data["aero"]["airfoils"])
            st.write(data["aero"]["bem"])  
        with m3:
            st.write(data["laminates"]["slabs"])
            st.write(data["mesh"]["webs"])
    elif page == "Airfoils":
        st.divider()
        m1,m2,m3 = st.columns(3)
        with m2:
            st.write(data["planform"])
        with m1:
            st.write(data["aero"]["airfoils"])
            st.write(data["aero"]["bem"])  
        with m3:
            st.write(data["laminates"]["slabs"])
            st.write(data["mesh"]["webs"])
    elif page == "Stiffness":
        st.markdown(''':blue[---确定前面的菜单都有选择，然后点击蓝色按钮] ''')
        t1,t2,t3,t4 = st.columns(4)
        with t2:
            if st.button("Convert Hawcstab2"):
                st.markdown(''':blue[---Starting to  Convert OK to Hawcstab2 file format] ''')
                #os.system("./run_all.sh %s" %("step04"))
                
                f_c = open(os.path.join(run_base,"Struct","compare.log"))
                compare = f_c.read() 
                with st.empty():
                    for i in range(1200):
                        f = open(os.path.join(run_base,"Struct","check_state.log")) 
                        new = f.read()
                        #st.write(line)
                        if new == compare:
                            f.close()
                            break
                        #f.close()
                        time.sleep(1)                        
                        st.write(f"⏳ 已过去 {i+2} 秒")
                    f_c.close()
                    st.write(''':green[------Convert done] ''')
                
                            
        with t1:
            if st.button("New Stiffness"):
                os.system("./run_all.sh %s" %("step04"))
                f_c = open(os.path.join(run_base,"Struct","compare.log"))
                compare = f_c.read() 
                st.markdown('''**:blue[Starting do ANBA Solver, need 15-20 mins]**''')
                with st.empty():
                    for i in range(1200):
                        f = open(os.path.join(run_base,"Struct","check_state.log")) 
                        new = f.read()
                        #st.write(line)
                        if new == compare:
                            f.close()
                            break
                        #f.close()
                        time.sleep(1)
                        n_i = i + 2
                        st.write(f"⏳ 已过去 {n_i} 秒")
                    f_c.close()
                    st.markdown('''**:green[------Convert done]**''')
            
            with t3:
                st.write('''**:blue[Stiffness 6x6 by sections]**''')
                foils_dir = os.path.join(run_base,'Struct','stiffness')
                air_file_list = []
                for file in os.listdir(foils_dir):
                    air_file_list.append(file)
                data_json = {}
                list_inputs_dir = os.path.join(run_base,"Struct/stiffness")
                #list_files = os.listdir(list_inputs_dir)
                file_ch = st.selectbox("pick a matrix of 6x6", (air_file_list))
                already__run =  True
                if file_ch is not None and already__run:
                    ext_file = os.path.join(list_inputs_dir,file_ch)
                    #st.write(ext_file)
                    with open(ext_file,'r', encoding=u'utf-8', errors='ignore') as fr:
                        data_json = json.load(fr)
                    #data_json = pd.read_json(ext_file)
                    st.write(data_json['stiffness']) 
                else:
                                
                    ext_file = os.path.join(run_base,'Struct','msec_60000.xdmf.json')
                    with open(ext_file,'r', encoding=u'utf-8', errors='ignore') as fr:
                        data_json = json.load(fr)
                    st.write(data_json['stiffness'])
    if page == "Stability":
        #run shell and dispay result
        st.markdown(''':blue[---稳定性分析分叶片和风机，图一是有问题的，图二和图三是本次实例计算结果] ''')
        list_inputs_dir = os.path.join(run_base,"stab2")
        st.image(os.path.join(list_inputs_dir,"campbell_analysis.png"))
        st.divider()
        st.image(os.path.join(list_inputs_dir,"campbell_structural.png"))
        st.divider()
        st.image(os.path.join(run_base,"stab2","damping_structural.png"))
        
if __name__=="__main__":
    css = """
        table 
        {
        border-collapse: collapse;
        }
        th
        {
        color: #ffffff;
        background-color: #000000;
        }
        td
        {
        background-color: #cccccc;
        }
        table, th, td
        {
        font-family:Arial, Helvetica, sans-serif;
        border: 1px solid black;
        text-align: right;
        }
    """
    main()


